home *** CD-ROM | disk | FTP | other *** search
- Path: damage.usa1.net!news
- From: crb3@usa1.com (crb3@usa1.com)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Mon, 22 Jan 1996 00:36:05 GMT
- Organization: USAinternet, Inc.
- Message-ID: <4dum0o$nsq@damage.usa1.net>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net> <4drjkc$il4@news.gate.net>
- NNTP-Posting-Host: wmn1-147.usa1.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- Quoth bhutto@gate.net (William Hutto):
-
- >;
- >;Given some number, there is a neat trick to generate a mask which will
- >;have exactly one bit set in it. The bit set will be the least
- >;significant non-zero bit in the original number:
- >;
- >; mask = ~number & number;
-
- >It's faster just to use:
-
- >mask = 0;
-
- >;
- >;Now, if number contained a single non-zero bit (and is therefore a
- >;power of 2), mask will be equal to number. Therefore:
- >;
- >; if (number == (~number & number))
-
- > if(!number)
-
- >; {
- >; /* number is a power of 2 */
-
- > /* number == 0 */
-
- >; }
- >;
-
- >Bill
-
- >"Whatcha got on?...Your mind?"
-
- You're right, as shown it zeroes out, but take another look.
- The quoted neat trick is broken, but there is something there (I had
- to play it out on paper and HP16 to see for myself :) ). It works if
- you use the unary-minus (2's-comp) operator rather than the bitwise
- negation (1's-comp) operator on the first RH arg:
-
- if( val == ( (-val) & val) )
- return(TRUE);
-
- Thanks for the neat trick btw
-
- --cr
-
-